package meta.api.web.operation.presentation;

import java.util.ArrayList;
import java.util.List;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import meta.api.web.account.businessinfo.UserInfo;
import meta.api.web.common.util.ApiUtil;
import meta.api.web.operation.businesscontrol.OpnMngBusiCtrl;
import meta.api.web.operation.businessinfo.ValueInfo;
import meta.api.web.operation.presentation.form.UserForm;
import meta.api.web.operation.presentation.form.UserListResult;
import meta.api.web.operation.presentation.form.ValueForm;
import meta.api.web.operation.presentation.form.ValueListResult;
import meta.common.log.CmnLogger;
import meta.common.msg.MessageConst;
import meta.common.util.JsonUtil;

@Controller
@RequestMapping(value="api/operation")
@Tag(name = "运营管理机能", description = "运营管理机能")
public class OpnMngController {

    private static final CmnLogger logger = CmnLogger.getLogger(OpnMngController.class);

    private static final String FUNC_NM = "运营管理机能";

    private static final String ERROR_MSG_DATA_ERROR= "请求数据错误";
    private static final String ERROR_MSG_ACCOUNT_EXIST = "账号已存在";
    private static final String ERROR_MSG_ACCOUNT_ID_NOT_EXIST = "账号ID不存在";
    private static final String ERROR_MSG_GET_USER_LIST_ERROR= "获取用户列表失败";
    private static final String ERROR_MSG_ADD_USER_ERROR= "添加用户失败";
    private static final String ERROR_MSG_UPDATE_USER_ERROR= "更新用户失败";
    private static final String ERROR_MSG_DELETE_USER_ERROR= "删除用户失败";
    private static final String ERROR_MSG_GET_VALUE_LIST_ERROR= "获取值列表失败";
    private static final String ERROR_MSG_SAVE_VALUE_ERROR= "新增/更新值失败";
    private static final String ERROR_MSG_DELETE_VALUE_ERROR= "删除值失败";

    @Autowired
    private OpnMngBusiCtrl opnMngBusiCtrl;

    /**
     * 获取用户列表
     * 
     * @param req 请求
     * @param res 响应
     * @param current 当前页
     * @param pageSize 每页记录数
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/account/list")
    @Operation(tags = "获取用户列表", description = "获取用户列表")
    public String listAccount(HttpServletRequest req, HttpServletResponse res,
            @RequestParam(value = "current", required = false) Integer current,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "获取用户列表", null);

        UserForm userForm = JsonUtil.toObj(ApiUtil.readTxtBody(req), UserForm.class);

        // if (userForm == null) {
        //     ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
        //     return null;
        // }

        int total;
        List<UserInfo> userList= new ArrayList<UserInfo>();
        try {
            // 获取用户总件数
            total = opnMngBusiCtrl.getUserTotal(
                    userForm == null ? null : userForm.getQuery());

            // 获取用户列表
            if (total > 0) {
                userList = opnMngBusiCtrl.getUserList(
                        userForm == null ? null : userForm.getQuery(), current, pageSize);
            }

            UserListResult result = new UserListResult();
            result.setTotal(total);
            result.setList(userList);

            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(result));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_USER_LIST_ERROR);
        }

        return null;
    }

    /**
     * 添加用户
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/account/add")
    @Operation(tags = "添加用户", description = "添加用户")
    public String addAccount(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "添加用户", null);

        UserInfo inputUser = JsonUtil.toObj(ApiUtil.readTxtBody(req), UserInfo.class);

        if (inputUser == null) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        try {
            // 检证账号是否存在
            if (opnMngBusiCtrl.checkExistAccount(inputUser.getAccount())) {
                // 存在的场合，返回错误
                ApiUtil.setErrorJsonResponse(res, ERROR_MSG_ACCOUNT_EXIST);
                return null;
            }

            // rebuild
            inputUser.rebuildByAccount();

            // 添加新用户
            opnMngBusiCtrl.addUser(inputUser);

            // 取得新用户详细情报
            UserInfo outputUser = opnMngBusiCtrl.getUser(inputUser.getAccount(), false);

            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(outputUser));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_ADD_USER_ERROR);
        }

        return null;
    }

    /**
     * 更新用户
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/account/update")
    @Operation(tags = "更新用户", description = "更新用户")
    public String updateAccount(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "更新用户", null);

        UserInfo inputUser = JsonUtil.toObj(ApiUtil.readTxtBody(req), UserInfo.class);

        if (inputUser == null) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        try {
            // 检证账号ID是否存在
            if (!opnMngBusiCtrl.checkExistAccountId(inputUser.getId())) {
                // 不存在的场合，返回错误
                ApiUtil.setErrorJsonResponse(res, ERROR_MSG_ACCOUNT_ID_NOT_EXIST);
                return null;
            }

            // 检证账号是否被其它用户占用
            if (opnMngBusiCtrl.checkAccountUsedByOther(inputUser.getId(), inputUser.getAccount())) {
                // 占用的场合，返回错误
                ApiUtil.setErrorJsonResponse(res, ERROR_MSG_ACCOUNT_EXIST);
                return null;
            }

            // rebuild
            inputUser.rebuildByAccount();

            // 更新用户
            opnMngBusiCtrl.updateUser(inputUser);

            // 取得更新用户详细情报
            UserInfo outputUser = opnMngBusiCtrl.getUser(inputUser.getAccount(), false);

            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(outputUser));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_UPDATE_USER_ERROR);
        }

        return null;
    }

    /**
     * 删除用户
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/account/delete")
    @Operation(tags = "删除用户", description = "删除用户")
    public String deleteAccount(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "删除用户", null);

        UserInfo inputUser = JsonUtil.toObj(ApiUtil.readTxtBody(req), UserInfo.class);

        if (inputUser == null) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        try {
            // 删除用户
            opnMngBusiCtrl.deleteUser(inputUser.getId());

            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DELETE_USER_ERROR);
        }

        return null;
    }

    /**
     * 获取值列表
     * 
     * @param req 请求
     * @param res 响应
     * @param current 当前页
     * @param pageSize 每页记录数
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/value/list")
    @Operation(tags = "获取值列表", description = "获取值列表")
    public String listValue(HttpServletRequest req, HttpServletResponse res,
            @RequestParam(value = "current", required = false) Integer current,
            @RequestParam(value = "pageSize", required = false) Integer pageSize) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "获取值列表", null);

        ValueForm valueForm = JsonUtil.toObj(ApiUtil.readTxtBody(req), ValueForm.class);

        if (valueForm == null || !valueForm.checkRequiredField4Opn()) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        int total;
        List<Object> valueList= new ArrayList<Object>();
        try {
            // 获取值总件数
            total = opnMngBusiCtrl.getValueTotal(
                    valueForm.getType(), valueForm.getQueryForKey());

            // 获取值列表
            if (total > 0) {
                valueList = opnMngBusiCtrl.getValueList(
                        valueForm.getType(), valueForm.getQueryForKey(),
                        current, pageSize);
            }

            ValueListResult result = new ValueListResult();
            result.setTotal(total);
            result.setList(valueList);

            ApiUtil.setJsonResponse(res, JsonUtil.toJsonStr(result));
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_GET_VALUE_LIST_ERROR);
        }

        return null;
    }

    /**
     * 新增/更新值
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/value/set")
    @Operation(tags = "新增/更新值", description = "新增/更新值")
    public String setValue(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "新增/更新值", null);

        ValueInfo value = JsonUtil.toObj(ApiUtil.readTxtBody(req), ValueInfo.class);

        if (value == null || !value.checkRequiredField4Save()) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        try {
            // 新增/更新值
            opnMngBusiCtrl.saveValue(value);

            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_SAVE_VALUE_ERROR);
        }

        return null;
    }

    /**
     * 删除值
     * 
     * @param req 请求
     * @param res 响应
     * @return
     * @throws Exception 异常
     */
    @PostMapping(value="/value/delete")
    @Operation(tags = "删除值", description = "删除值")
    public String deleteValue(HttpServletRequest req, HttpServletResponse res) throws Exception {
        ApiUtil.callApiLog(req, FUNC_NM, "删除值", null);

        ValueInfo value = JsonUtil.toObj(ApiUtil.readTxtBody(req), ValueInfo.class);

        if (value == null || !value.checkRequiredField4Delete()) {
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DATA_ERROR);
            return null;
        }

        try {
            // 删除值
            opnMngBusiCtrl.deleteValue(value);

            ApiUtil.setEmptyJsonResponse(res);
        } catch (Exception e) {
            logger.log(MessageConst.MSG_01090001, null, e);
            ApiUtil.setErrorJsonResponse(res, ERROR_MSG_DELETE_VALUE_ERROR);
        }

        return null;
    }
}
